package com.imflea.zero.controller.task;

import com.imflea.zero.util.ZeroCacheUtils;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.constant.QxContant;
import com.imflea.zero.model.entity.qx.QxUserAccess;
import com.imflea.zero.model.entity.user.vo.UserAccessVo;
import com.imflea.zero.service.qx.IQxUserAccessService;
import com.imflea.zero.service.task.IScheduledTaskJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 祥保玉
 * @PackageName: com.imflea.zero.controller.task
 * @ClassName: WebUserTasklController
 * @Description
 * @date 2022-01-13  16:07:14
 */
@Component
@Slf4j
public class WebUserTaskJob implements IScheduledTaskJobService {
    @Autowired
    private IQxUserAccessService userAccessService;


    @Override
    public void run() {
        log.error("用户访问量定时计算");
        Set<String> keys = null;
        List<UserAccessVo> result = new ArrayList<>();
        List<QxUserAccess> userAccesses = new ArrayList<>();

        try {
            keys =ZeroCacheUtils.getKeys(QxContant.getWxAccessUserNumPrefix() + "*");
            for (String key : keys) {
                UserAccessVo item = new UserAccessVo();
                String[] per = key.split(":");
                item.setTenantId(per[1]);
                item.setUserId(per[2]);
                result.add(item);
            }
            Map<String, Long> userAccessData = result.parallelStream().collect(Collectors.groupingBy(UserAccessVo::getTenantId, Collectors.counting()));
            for (String tenantId : userAccessData.keySet()) {
                QxUserAccess access = new QxUserAccess();
                access.setId(CommonUtils.generateRandomString());
                access.setAccessDay(LocalDate.now());
                access.setTenantId(tenantId);
                access.setTotal(userAccessData.get(tenantId));
                access.setCreateUserId("robot");
                access.setCreateUserName("robot");
                access.setUpdateUserId("robot");
                access.setUpdateUserName("robot");
                this.userAccessService.saveOrUpdateByTenantAndDate(access);
                userAccesses.add(access);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
